package com.briup.estore.web.servlet;

import com.briup.estore.bean.Customer;
import com.briup.estore.service.CustomerService;
import com.briup.estore.service.Impl.CustomerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * 登录逻辑
 */
@WebServlet("/userLogin")
public class LoginServlet extends HttpServlet {
    private CustomerService customerService;
    {
        customerService =new CustomerServiceImpl();
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数
        String username = req.getParameter("name");
        String password = req.getParameter("password");
        //调用service
        //获得用户
        Customer user = customerService.login(username, password);
        HttpSession session = req.getSession();
        session.setAttribute("user",user);
        //分发页面
        if (user == null){
            session.setAttribute("msg","登陆失败，请重新登录");
            resp.sendRedirect("login");
        }else {
            session.setAttribute("msg","登陆成功");
            session.setAttribute("user",user);
            Cookie cookie=new Cookie("userId",user.getId()+"");
            //设置7天有效
            cookie.setMaxAge(3600*24*7);
            resp.addCookie(cookie);
            resp.sendRedirect("index_data");
        }
    }
}
